package com.liseen.net
{
	import com.liseen.events.SmartSocketEvent;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	/**
	 * Sokcket通讯体
	 * @author Liseen
	 * 
	 */	
	public class SmartSocket extends Socket
	{
		private static var instance:SmartSocket;
		
		private var _port:uint;
		private var _host:String;
		public function SmartSocket(value:Singleton)
		{
			this.addEventListener(Event.CONNECT,onSocketConnetHandle);
			this.addEventListener(Event.CLOSE,onSocketCloseHandle);
			this.addEventListener(IOErrorEvent.IO_ERROR,onIOErrorHandle);
			this.addEventListener(ProgressEvent.SOCKET_DATA,onProgressHandle);
			this.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityErrorHandle);
		}
		/**
		 *获取服务器通讯机体 SmartSocket
		 * @return 
		 * 
		 */		
		public static function getInstance():SmartSocket
		{
			if(SmartSocket.instance == null)
			{
				SmartSocket.instance = new SmartSocket(new Singleton());
				
			}
			
			return SmartSocket.instance;
		}
		/**
		 *链接Socket服务器 
		 * @param host		主机
		 * @param port		端口号
		 * 
		 */		
		override public function connect(host:String, port:int):void
		{
			if(this.connected)
			{
				return;
			}
			this._host = host;
			this._port = port;
			
			super.connect(this._host,this._port);
		}
		/**
		 *发送数据 
		 * @param data	数据
		 * 
		 */		
		public function send(data:ByteArray):void
		{
			if(!this.connected||data==null)
			{
				return;
			}
			
			if (data)
			{
				this.writeBytes(data, 0, data.length);
				this.flush();
			}
		}
		/**
		 *是否已链接到服务器 
		 * @return 
		 * 
		 */		
		public function get isConneted():Boolean
		{
			return this.connected	
		}
		/**
		 *获取主机地址 
		 * @return 
		 * 
		 */		
		public function get host():String
		{
			return this._host;	
		}
		/**
		 *获取端口号 
		 * @return 
		 * 
		 */		
		public function get port():int
		{
			return this._port;	
		}
		
		private function onSocketConnetHandle(event:Event):void
		{
			this.dispatchEvent(new SmartSocketEvent(SmartSocketEvent.CONNECT));
		}
		
		private function onSocketCloseHandle(event:Event):void
		{
			this.dispatchEvent(new SmartSocketEvent(SmartSocketEvent.CLOSE));
		}
		
		private function onIOErrorHandle(event:IOErrorEvent):void
		{
			this.dispatchEvent(new SmartSocketEvent(SmartSocketEvent.IO_ERROR));	
		}
		
		private function onProgressHandle(event:ProgressEvent):void
		{
			this.dispatchEvent(new SmartSocketEvent(SmartSocketEvent.RECEIVED));	
		}
		
		private function onSecurityErrorHandle(event:SecurityErrorEvent):void
		{
			this.dispatchEvent(new SmartSocketEvent(SmartSocketEvent.SECURITY_ERROR));	
		}
		
	}
}

class Singleton 
{
	
	
}